
/**
 * request封装
 */
const {COM_URL } = require("@/utils/config")
function request(url, data = {}, method = "GET", contentType = {}, token,isHidden) {
	return new Promise(function(resolve, reject) {
		if(!isHidden ){
			uni.showLoading({
				title: '加载中'
			});
		}
	
		
		let headerData = {}
		headerData['content-type'] = contentType;
		if(token){
			headerData[token] = uni.getStorageSync('token');
		}

		//因为我们的GET和POST请求结构不同这里我们做处理，大家根据自己后台接口所需结构灵活做调整
		if (method == "GET") {
			// data.t = new Date().getTime();
			// data.r = Math.floor(Math.random() * 10000);

		}else{
			// dataObj = {
			//     'data': data,
			//     'token': uni.getStorageSync('token')
			// }
		}
		
		uni.request({
			url: url,
			data: data,
			header: headerData,
			method: method,
			success: function(res) {
				// uni.hideLoading();

				// console.log(res)
				if(!isHidden || url.indexOf('common/userLogin')>=0){
					uni.hideLoading();
				
				}
				//这里是成功的返回码，大家根据自己的实际情况调整
				if (res.data.code =='401' ) {
					uni.reLaunch({
						url:'/pages/index/index'
					  })
				}else {
					
					resolve(res.data);

				}
			},
			fail: function(err) {
				uni.showToast({
					title:'网络异常',
					icon:'none',
					duration:1500
				})
				reject(err);
			
			},
			complete: () => {
				if(!isHidden){
					uni.hideLoading()

				}
			}
		});
	});
}

/**
 * get请求
 */
function get(url, data = {},contentType,token,isHidden) {

	return request(url, data, 'GET',contentType,token,isHidden);
}

/**
 * post请求
 */
function post(url, data = {},contentType,token,isHidden) {
	return request(url, data, 'POST',contentType,token,isHidden);
}
function put(url, data = {},contentType,token) {
	// console.log(contentType,'cotne')
	return request(url, data, 'PUT',contentType,token);
}
function del(url, data = {},contentType,token) {

	return request(url, data, 'DELETE',contentType,token);
}
module.exports = {
	get,
	post,
	put,
	del
};
